package com.fjwt.gz.mgr.ctrl.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.aop.MethodLog;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.core.utils.StringKit;
import com.fjwt.gz.db.entity.SysConfig;
import com.fjwt.gz.mgr.ctrl.CommonCtrl;
import com.fjwt.gz.service.impl.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 系统配置信息类
 *
 * @author pangxiaoyu
 * @site https://pt.jdyd.xyz/
 * @date 2021-06-07 07:15
 */
@Slf4j
@RestController
@RequestMapping("api/sysConfigs")
public class SysConfigController extends CommonCtrl {

	@Autowired private SysConfigService sysConfigService;


	/**
	 * @author: pangxiaoyu
	 * @date: 2021/6/7 16:19
	 * @describe: 分组下的配置
	 */
	@PreAuthorize("hasAnyAuthority('ENT_SYS_CONFIG_INFO', 'ENT_SYS_CONFIG_VIEW', 'ENT_PUSH_CONFIG_VIEW')")
	@RequestMapping(value="/{groupKey}", method = RequestMethod.GET)
	public ApiRes getConfigs(@PathVariable("groupKey") String groupKey) {
		LambdaQueryWrapper<SysConfig> condition = SysConfig.gw();
		condition.orderByAsc(SysConfig::getSortNum);
		if(StringUtils.isNotEmpty(groupKey)){
			condition.eq(SysConfig::getGroupKey, groupKey);
		}
		List<SysConfig> configList = sysConfigService.list(condition);

		// 数据脱敏
		this.autoDesen(configList);

		//返回数据
		return ApiRes.ok(configList);
	}

	/**
	 * @author: pangxiaoyu
	 * @date: 2021/6/7 16:19
	 * @describe: 系统配置修改
	 */
	@PreAuthorize("hasAnyAuthority('ENT_SYS_CONFIG_EDIT', 'ENT_PUSH_CONFIG_EDIT')")
	@MethodLog(remark = "系统配置修改")
	@RequestMapping(value="/{groupKey}", method = RequestMethod.PUT)
	public ApiRes update(@PathVariable("groupKey") String groupKey) {
		log.info("修改系统配置：{}", groupKey);
		JSONObject paramJSON = getReqParamJSON();
		Map<String, String> updateMap = new HashMap<>();
		if ("smsConfig".equals(groupKey)) {

			// 合并
			updateMap.put("smsConfigValue", StringKit.marge(sysConfigService.getById("smsConfigValue").getConfigVal(), paramJSON.toJSONString()));

		}else if ("ossConfig".equals(groupKey)) {

			// 合并
			updateMap.put("aliyunOssConfig", StringKit.marge(sysConfigService.getById("aliyunOssConfig").getConfigVal(), paramJSON.getString("aliyunOssConfig")));
			updateMap.put("ossUseType", paramJSON.getString("ossUseType"));

		}else if ("oemConfig".equals(groupKey)) {
			paramJSON.put("mgr", paramJSON.getJSONObject("mgr"));
			paramJSON.put("mch", paramJSON.getJSONObject("mch"));
			paramJSON.put("agent", paramJSON.getJSONObject("agent"));
			updateMap.put("oemConfig", paramJSON.toJSONString());

		}else if ("defaultConfig".equals(groupKey)) {

			updateMap = (Map<String, String>) JSONObject.parseObject(JSONObject.toJSONString(paramJSON), Map.class);

			// 处理 密码格式  解密 + 保存为DB格式,
			if(StringUtils.isNotEmpty(updateMap.get("defaultPassword") ) ) {

				// 20220406改为  encode格式，可以解密（通知短信需要查看密码原文）
//				String defaultPassword = new BCryptPasswordEncoder().encode(Base64.decodeStr(getValStringRequired("defaultPassword")));
//				updateMap.put("defaultPassword", defaultPassword);

			}else{
				updateMap.remove("defaultPassword");
			}

		}else {
			Map<String, String> map = (Map<String, String>) JSONObject.parseObject(JSONObject.toJSONString(paramJSON), Map.class);

			for (String key : map.keySet()) {
				// 脱敏数据 && 记录为空 = 不更新
				if(desenKeys.contains(key) && StringUtils.isEmpty(map.get(key))){
					continue;
				}
				updateMap.put(key, map.get(key));
			}
		}
		int update = sysConfigService.updateByConfigKey(updateMap);
		if(update <= 0) {
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, "更新失败");
        }

		// 异步更新到MQ
		SpringBeansUtil.getBean(SysConfigController.class).updateSysConfigMQ(groupKey);

		return ApiRes.ok();
	}

	@Async
	public void updateSysConfigMQ(String groupKey){
//		mqSender.send(ResetAppConfigMQ.build(groupKey));
	}


	/** 过滤脱敏数据 */
	private void autoDesen(List<SysConfig> sysConfigList){

		if(sysConfigList == null){
			return;
		}

		for (SysConfig sysConfig : sysConfigList) {
			if (desenKeys.contains(sysConfig.getConfigKey())){
				sysConfig.addExt("configValDesen", StringKit.autoDesensitization(sysConfig.getConfigVal()));
				sysConfig.setConfigVal(null);
			}

			// 短信配置 特殊处理
			if("smsConfigValue".equals(sysConfig.getConfigKey())){
				JSONObject jsonObject = JSON.parseObject(sysConfig.getConfigVal());
				jsonObject.put("accessKeySecret", StringKit.autoDesensitization(jsonObject.getString("accessKeySecret")));

				// 原始文件删除配置项，  在外层增加加密脱敏数据。
				sysConfig.addExt("configValDesen", jsonObject.toJSONString());
				jsonObject.remove("accessKeySecret");
				sysConfig.setConfigVal(jsonObject.toJSONString());

			}else if("aliyunOssConfig".equals(sysConfig.getConfigKey())){ // OSS 特殊处理
					JSONObject jsonObject = JSON.parseObject(sysConfig.getConfigVal());
					jsonObject.put("accessKeySecret", StringKit.autoDesensitization(jsonObject.getString("accessKeySecret")));

					// 原始文件删除配置项，  在外层增加加密脱敏数据。
					sysConfig.addExt("configValDesen", jsonObject.toJSONString());
					jsonObject.remove("accessKeySecret");
					sysConfig.setConfigVal(jsonObject.toJSONString());
				}
		}

	}

	// 脱敏key
	private static final Set<String> desenKeys = new HashSet<>();
	static{
		desenKeys.add("uniPushMasterSecret"); //app推送 ： uniPush_masterSecret
		desenKeys.add("apiMapWebSecret"); //高德地图配置
	}

}
